package best.driver.android.common.push;

import best.driver.android.common.app.AppProxyFactory;
import best.driver.android.common.network.ApiJsonRequest;
import best.driver.android.common.network.ApiRequest;
import best.driver.android.common.network.BestError;
import org.json.JSONObject;

public abstract class PushDeviceTokenBinder implements IPushDeviceTokenBinder {

    private PushDeviceTokenBinderListener mListener;
    private ApiJsonRequest mApiRequest;

    @Override
    public void uploadDeviceToken(String token) {
        mApiRequest = createUploadTokenRequest(token);
        mApiRequest.setListener(new UploadTokenApiRequestListenerImpl());
        AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(mApiRequest);
    }

    @Override
    public void unbindDeviceToken(String token) {
        mApiRequest = createUnbindDeviceTokenRequest(token);
        mApiRequest.setListener(new UnbindTokenApiRequestListenerImpl());
        AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(mApiRequest);
    }

    @Override
    public void cancelProcess() {
        if (mApiRequest != null) {
            mApiRequest.cancel();
            mApiRequest = null;
        }
    }

    @Override
    public PushDeviceTokenBinderListener getListener() {
        return mListener;
    }

    @Override
    public void setListener(PushDeviceTokenBinderListener listener) {
        mListener = listener;
    }

    protected abstract ApiJsonRequest createUploadTokenRequest(String deviceToken);

    protected abstract ApiJsonRequest createUnbindDeviceTokenRequest(String deviceToken);

    private class UploadTokenApiRequestListenerImpl implements ApiRequest.ApiRequestListener<JSONObject> {

        @Override
        public void onRequestSuccess(JSONObject response) {
            if (getListener() != null) {
                getListener().onUploadDeviceTokenSuccess();
            }
        }

        @Override
        public void onRequestError(BestError error) {
            if (getListener() != null) {
                getListener().onUploadDeviceTokenFailed(error);
            }
        }
    }

    private class UnbindTokenApiRequestListenerImpl implements ApiRequest.ApiRequestListener<JSONObject> {

        @Override
        public void onRequestSuccess(JSONObject response) {
            if (getListener() != null) {
                getListener().onUnbindDeviceTokenSuccess();
            }
        }

        @Override
        public void onRequestError(BestError error) {
            if (getListener() != null) {
                getListener().onUnbindDeviceTokenFailed(error);
            }
        }
    }
}
